package com.dragon.codefx.constant;

import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

/**
 * 支持的数据库类型枚举
 */
@Getter
public enum DatabaseType {
    MYSQL("mysql", "com.mysql.cj.jdbc.Driver", "SELECT 1"),
    ORACLE("oracle", "oracle.jdbc.driver.OracleDriver", "SELECT 1 FROM DUAL"),
    SQLSERVER("sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "SELECT 1"),
    SQLITE("sqlite", "org.sqlite.JDBC", "SELECT 1"),
    POSTGRESQL("postgresql", "org.postgresql.Driver", "SELECT 1"),
    H2("h2", "org.h2.Driver", "SELECT 1"),
    MARIADB("mariadb", "org.mariadb.jdbc.Driver", "SELECT 1");

    private final String urlPrefix;      // JDBC URL前缀
    private final String driverClass;   // 驱动类名
    private final String validationQuery; // 连接验证查询语句

    DatabaseType(String urlPrefix, String driverClass, String validationQuery) {
        this.urlPrefix = urlPrefix;
        this.driverClass = driverClass;
        this.validationQuery = validationQuery;
    }

    /**
     * 根据JDBC URL获取对应的数据库类型
     */
    public static DatabaseType fromJdbcUrl(String jdbcUrl) {
        if (StringUtils.isBlank(jdbcUrl)) {
            throw new IllegalArgumentException("JDBC URL不能为空");
        }

        String url = jdbcUrl.toLowerCase();
        for (DatabaseType type : values()) {
            if (url.startsWith("jdbc:" + type.urlPrefix)) {
                return type;
            }
        }
        throw new IllegalArgumentException("不支持的数据库类型: " + jdbcUrl);
    }
}